package com.lagou.edu;

import com.alibaba.fastjson.JSON;
import com.lagou.edu.config.DataSourceProvider;
import com.lagou.edu.source.CustomizeHikariDataSource;
import com.lagou.edu.source.DataSourceInfo;
import com.lagou.edu.utils.ZookeeperFactory;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;

/**
 * @author 赵虎
 */
@SpringBootApplication
@EnableTransactionManagement
@MapperScan(basePackages = "com.lagou.edu.mapper")
public class ZookeeperDynamicDatabaseApplication {

    @Autowired
    private CustomizeHikariDataSource customizeHikariDataSource;

    public static void main(String[] args) {
        SpringApplication.run(ZookeeperDynamicDatabaseApplication.class, args);
    }

    @PostConstruct
    public void startReadZk() throws Exception {
        ZookeeperFactory zookeeperFactory = ZookeeperFactory.getInstance("10.10.10.205", 2181);

        DataSourceInfo sourceInfo = zookeeperFactory.getPathValue(ZookeeperFactory.zkNodeName, DataSourceInfo.class);
        if (sourceInfo != null) {
            customizeHikariDataSource.setDataSourceMap(DataSourceProvider.create(sourceInfo));
        }

        NodeCache nodeCache = zookeeperFactory.getNodeCache(ZookeeperFactory.zkNodeName);
        nodeCache.getListenable().addListener(() -> {
            byte[] data = nodeCache.getCurrentData().getData();
            String s = new String(data, StandardCharsets.UTF_8);
            DataSourceInfo dataSourceInfo = JSON.parseObject(s, DataSourceInfo.class);
            if (dataSourceInfo != null) {
                customizeHikariDataSource.setDataSourceMap(DataSourceProvider.create(dataSourceInfo));
            }
        });
    }
}
